package com.wens.baselibrary.view.activity

import android.content.Context
import android.os.Bundle
import android.view.KeyEvent
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.BarUtils
import com.trello.rxlifecycle4.components.support.RxAppCompatActivity
import com.wens.baselibrary.R
import com.wens.baselibrary.present.BasePresent
import com.wens.baselibrary.util.RxUtil
import com.wens.baselibrary.view.BaseView
import com.wens.baselibrary.view.dialog.BackDialog
import com.wens.baselibrary.view.dialog.BaseDialog
import com.wens.baselibrary.view.dialog.ProgressDialog
import java.util.*

abstract class BaseActivity<P : BasePresent> : RxAppCompatActivity(), BaseView {
    protected val present: P by lazy { createPresent() }

    protected abstract fun createPresent(): P

    private val functionUse = HashMap<String, String>()
    private val repeatableFunctionUse = HashMap<String, HashMap<String, ArrayList<String>>>()
    private val progressDialog: BaseDialog by lazy {
        onCreateProgressDialog()
            .setCancelable(isProgressDialogCancelable)
    }

    private var backDialog: BaseDialog? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ARouter.getInstance().inject(this)
        BarUtils.setStatusBarVisibility(this, false)
        if (isShowBackDialog) backDialog = BackDialog(this)
            .setOkClickListener {
                if (isShowBackAd) showBackAd()
                super.onBackPressed()
            }.setCancelable(true)
        initView(this)
        initData(this)
    }

    protected open fun showBackAd() {

    }

    protected open val isShowBackDialog: Boolean
        get() = true
    protected open val isShowBackAd: Boolean
        get() = false

    protected open val isProgressDialogCancelable: Boolean
        get() = false

    fun showProcessDialog() {
        progressDialog.show()
    }

    fun dismissProcessDialog() {
        progressDialog.dismiss()
    }

    protected open fun onCreateProgressDialog(): ProgressDialog {
        return ProgressDialog(this, R.layout.progress_dialog)
    }

    override fun onBackPressed() {
        if (isShowBackDialog) backDialog?.show() else {
            if (isShowBackAd) showBackAd()
            super.onBackPressed()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        RxUtil.dispose(javaClass)
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (progressDialog.onKeyDown(keyCode, event)) return true
        return if (backDialog != null && backDialog!!.onKeyDown(
                keyCode,
                event
            )
        ) true else super.onKeyDown(keyCode, event)
    }

    override fun getContext(): Context? = this
}